package cn.hloger.spider.common.global;

import cn.hloger.spider.common.annotation.PackagResp;
import cn.hloger.spider.common.bean.ApiResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局处理
 *
 * @author huanglong
 * @Description TODO
 * @data 2022/9/13
 */
@RestControllerAdvice
public class GlobalExceptionHandler implements ResponseBodyAdvice<Object> {

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Object> exceptionHandler(Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
                .body(ApiResponse.fail(e));
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    public ResponseEntity<Object> handleAuthenticationException(Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
                .body(ApiResponse.fail(e.getMessage()));
    }

    /**
     * 全局包装,这个方法用于判断是否应该应用这个Advice
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 你可以根据需要自定义条件，比如只对特定类型的返回值进行包装
//        return false;
        //有这个注解就拦截
        return returnType.getMethodAnnotation(PackagResp.class) != null;
//        return true;
    }

    // 全局包装,这个方法用于处理和包装返回值
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            throw new RuntimeException("AI也有回答不上的时候");
        }
        //字符串用专门的StringHttpMessageConverter 处理,如果包装会产生.ApiResponse cannot be cast to java.lang.String异常
        if (body instanceof ApiResponse || body instanceof String) {
            // 如果已经是ApiResponse或者String类型，直接返回
            return body;
        }
        // 将body包装成ApiResponse
        ApiResponse apiResponse = ApiResponse.success(body);
        return apiResponse;
    }
}
